package buaa.paas.kubectl;

import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodCondition;
import io.kubernetes.client.openapi.models.V1PodList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;

@Service
public class PodUtil {
    @Autowired
    ApiUtil util;
    /**
     * @param pod 被提取信息的pod
     * @return 返回的pod的信息，包括：名字，状态，启动时间，IP，所在的节点
     * */
    public static TreeMap<String, Object> briefPod(V1Pod pod){
        TreeMap<String, Object> result = new TreeMap<>();
        result.put("Name", pod.getMetadata().getGenerateName());
        result.put("IP", pod.getStatus().getPodIP());
        result.put("NodeName", pod.getSpec().getNodeName());
        result.put("StartTime", pod.getStatus().getStartTime().toString());
        result.put("Status", pod.getStatus().getPhase());
        TreeMap<String, String> conditions = new TreeMap<>();// pod的condition
        for(V1PodCondition c: pod.getStatus().getConditions()){
            conditions.put(c.getType(), c.getStatus());
        }
        result.put("Condition", conditions);
        return result;
    }

    /**
     * 获得一个namespace下面全部的pod
     * @param namespace 根据用户id和项目id一起生成的namespace
     * @return 一个列表，装着上面的那些东西
     * */
    public List<TreeMap<String, Object>> getPodsFromNamespace(String namespace) throws ApiException {
        V1PodList pList = util.getCoreApi().listNamespacedPod(namespace, null, null, null, null, null, null, null, null, null);
        LinkedList<TreeMap<String, Object>> result = new LinkedList<>();
        for(V1Pod p: pList.getItems()){
            result.addLast(briefPod(p));
        }
        return result;
    }
}
